package com.shujia.spark.core

import org.apache.spark.broadcast.Broadcast
import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}

object Demo17Bro {
  def main(args: Array[String]): Unit = {
    val conf = new SparkConf()
    conf.setAppName("Demo17Bro")
    conf.setMaster("local")

    val sc = new SparkContext(conf)

    //获取总分前十学生的信息

    //1、计算学生的总分
    val sumScoreRDD: RDD[(String, Double)] = sc
      .textFile("data/score.txt")
      .map(_.split(","))
      .map { case Array(id, cId, score) => (id, score.toDouble) }
      .reduceByKey(_ + _)

    //2、取前十
    val ids: Array[String] = sumScoreRDD
      .sortBy { case (_, sumScore) => -sumScore }
      .take(10)
      .map { case (id, sumScore) => id }

    /**
     * 广播变量：当在算子内使用算子外的一个大变量时，同时task的数量远大于Executor数量时，可以将变量广播出去
     */
    //1、将变量广播到Executor端
    val broIds: Broadcast[Array[String]] = sc.broadcast(ids)

    //3、读取学生的信息
    val studentsRDD: RDD[String] = sc.textFile("data/students.txt")

    //4、取出前十学生的信息
    val top10RDD: RDD[String] = studentsRDD
      .filter(stu => {
        //取出学号
        val id: String = stu.split(",").head

        //2、获取广播变量
        broIds.value.contains(id)
      })

    top10RDD.foreach(println)
  }
}